package com.example.springboot.service.impl;

import com.example.springboot.common.Constants;
import com.example.springboot.common.ReserveStatus;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Seat;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.SeatMapper;
import com.example.springboot.service.ISeatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * <p>
 * 座位管理 服务实现类
 * </p>
 *
 * @author 
 * @since 
 */
@Service
@Slf4j
public class SeatServiceImpl extends ServiceImpl<SeatMapper, Seat> implements ISeatService {

    @Resource
    private SeatMapper seatMapper;


    @Transactional
    public Result reserveSeat(Integer seatId, LocalDateTime start, LocalDateTime end) {
        log.info("尝试预约座位: seatId={}, start={}, end={}", seatId, start, end);

        // 基本时间校验（移到try-catch外）
        if (start.isBefore(LocalDateTime.now())) {
            throw new ServiceException(Constants.CODE_600, "开始时间不能早于当前时间");
        }
        if (end.isBefore(start.plusMinutes(30))) {
            throw new ServiceException(Constants.CODE_600, "预约时间至少30分钟");
        }
        if (ChronoUnit.HOURS.between(start, end) > 4) {
            throw new ServiceException(Constants.CODE_600, "单次预约最多4小时");
        }

        try {
            // 冲突检测
            int conflictCount = seatMapper.checkConflict(seatId, start, end);
            if (conflictCount > 0) {
                throw new ServiceException(Constants.CODE_600, "时间冲突");
            }

            // 状态校验和更新
            Seat seat = getById(seatId);
            if (seat.getStatus() != ReserveStatus.AVAILABLE) {
                throw new ServiceException(Constants.CODE_600, "座位不可用");
            }

            // 获取当前用户完整信息
            User currentUser = TokenUtils.getCurrentUser();

            // 更新预约信息
            seat.setStartTime(start);
            seat.setEndTime(end);
            seat.setStatus(ReserveStatus.RESERVED);
            seat.setUserId(currentUser.getId());
            seat.setUserName(currentUser.getNickname()); // 新增用户名存储

            updateById(seat);
            return Result.success();

        } catch (Exception e) {
            log.error("预约处理失败: ", e);
            throw new ServiceException(Constants.CODE_500, "预约处理失败: " + e.getMessage());
        }
    }
}
